<?php
namespace App\Goods\Services;

use App\BaseService;
use App\Exceptions\GoodsException;
use App\Goods\Models\CommonName;
use App\Goods\Models\GoodsBase;
use App\Goods\Models\GoodsClassify;
use App\Goods\Handles\GoodsHandle;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GoodsBaseService extends BaseService
{
    use GoodsHandle;

    protected function setData($data)
    {
        $save_data =  [
            'sku_sn' => '',
            'spu_sn' => '',
            'common_name_id' => 0,
            'common_name' => '',
            'dosage' => '',
            'product_name' => '',
            'goods_name' => '',
            'trade_name' => '',
            'english_name' => '',
            'pinyin' => '',
            'batch_sn' => '',
            'cert_sn' => '',
            'product_address' => '',
            'approve_date' => 0,
            'end_date' => 0,
            'spec' => '',
            'type_one' => 0,
            'type_two' => 0,
            'type_three' => 0,
            'type_four' => 0,
            'type_line' => '',
            'small_pack' => '',
            'pack_scale' => '',
            'big_pack' => '',
            'special_scale' => '',
            'special_pack' => '',
        ];
        foreach($data as $k => $v){
            if(!isset($save_data[$k])){
                continue;
            }
            $save_data[$k] = $v;
        }
        $save_data['approve_date'] = strtotime($save_data['approve_date']);
        $save_data['end_date'] = strtotime($save_data['end_date']);

        return $save_data;
    }

    /**
     * 添加商品基本信息
     * @param $data
     * @return bool
     * @throws GoodsException
     */
    public function save($data)
    {
        // 查询通用名
        $common_name = CommonName::find($data['common_name_id']);
        if(!$common_name){
            throw new GoodsException('通用名不存在或已删除！');
        }
        $data['common_name'] = $common_name->name;
        // 分类处理
        $type_line = [
            $data['type_one'],
            $data['type_two'],
            $data['type_three'],
            $data['type_four'],
        ];
        $data['type_line'] = implode('-', $type_line);
        // 生成sku_sn
        $data['spu_sn'] = $common_name->spu_sn;
        $sku_sn = $this->setSkuHandle($common_name->spu_sn);
        $data['sku_sn'] = $sku_sn;
        $save_data = $this->setData($data);
        DB::beginTransaction();
        try{
            // 添加数据
            if(!$goods_base = GoodsBase::create($save_data)){
                throw new GoodsException('添加失败！');
            }
            // 添加属性
            $attr = json_decode($data['attr']);
            $attr_arr = [];
            foreach($attr as $v){
                $attr_arr[$v->id] = [
                    'value' => $v->value
                ];
            }
            $res = $goods_base->hasAttr()->sync($attr_arr);
            if(!$res){
                throw new Exception('添加属性失败！');
            }
            // 添加图片
            $images = json_decode($data['images']);
            $save_images = [];
            foreach($images as $k => $v){
                $save_images[$k]['base_id'] = $goods_base->id;
                $save_images[$k]['image'] = $v->url;
            }
            $res = $goods_base->hasImages()->insert($save_images);
            if(!$res){
                throw new Exception('添加图片失败！');
            }

            DB::commit();
            return $goods_base;
        }catch (Exception $exception){
            DB::rollBack();
            dd($exception->getMessage());
        }
    }

    /**
     * 显示商品详情
     * @param $param
     * @param string $type
     * @return Builder|Model|object
     * @throws GoodsException
     */
    public function info($param, $type = 'id')
    {
        $goods_base = GoodsBase::with(['hasAttr' => function ($table){
            $table->select(['name', 'type', 'value']);
        }, 'hasImages' => function ($table){
            $table->select(['id', 'base_id', 'image']);
        }])->where(function ($table) use ($param, $type){
            if($type == 'sku'){
                $table->where('sku_sn', $param);
            }else{
                $table->where('id', $param);
            }
        })->first();
        if(!$goods_base){
            throw new GoodsException('商品基本信息不存在或已删除！');
        }
        return $goods_base;
    }

}
